<?php


namespace utils;
use think\Response;
use constants\StatusCode;

/**
 * Json输出类
 * Class Json
 * @package crmeb\utils
 */
class Json
{
    private $code = 200;

    public function code(int $code): self
    {
        $this->code = $code;
        return $this;
    }

    public function make(int $status, string $msg = 'ok', $data = []): Response
    {
        $request = app()->request;
        if (config('api.is_carry_pid')) {
            $res['qid'] = $request->qid();
        }
        $res['code'] = $status;
        $res['msg'] = $msg;
        if (!empty($data)) {
            $res['data'] = $data;
        }

        return Response::create($res, 'json', $this->code);
    }

    public function success($data = [], $msg = '0k'): Response
    {
        $msg = $msg ?? StatusCode::getMessage(StatusCode::SUCCESS);
        return $this->make(StatusCode::SUCCESS, $msg, $data);
    }

    public function successful(...$args): Response
    {
        return $this->success(...$args);
    }

    public function error(int $code = StatusCode::ERR_EXCEPTION, string $msg = null): Response
    {

        $msg = $msg ?? StatusCode::getMessage($code);
        return $this->make($code, $msg, []);
    }

    public function status($status, $msg, $result = [])
    {
        $status = strtoupper($status);
        if (is_array($msg)) {
            $result = $msg;
            $msg = 'ok';
        }
        return $this->success($msg, compact('status', 'result'));
    }

}
